<template>
	<view class="album">
		<view class="select_img">
			<uni-file-picker limit="1" title="我的头像:" v-model="imageValue" :value="imageValue" fileMediatype="image" mode="grid" @select="select"/>
		</view>
		<view class="img_list">
			<uni-file-picker v-if="imageList.length>0" title="我的相册:" v-model="imageList" :value="imageValue" fileMediatype="image" mode="grid" @select="selectList" @delete="deleteOne">

			</uni-file-picker>
			<uni-file-picker v-else title="我的相册:" v-model="imageList" fileMediatype="image" mode="grid" @select="selectList"/>
		</view>
	</view>
</template>

<script setup>
import {onMounted, ref} from "vue";
import { useStore } from "vuex";
import { albumReq, album_addReq, album_delReq,update_headerReq } from "../../api/user";
import { baseUrl } from "../../utils/request";
	const store=useStore()
	// 头像
	const imageValue=ref([{url:store.state.user.curHeader}])
	// 相册
	const imageList=ref([])
	// 更新头像
	const update_header=async(header)=>{
		let res=await update_headerReq(header)
	}
	// 获取上传状态
	const select=(e)=> {
		uni.uploadFile({
			url: baseUrl+'/upload/img',
			name:'file',
			filePath:e.tempFiles[0].path,
			header: {
				token:store.state.user.data.token
			},
			success: (res) => {
				let resb=JSON.parse(res.data)
				const {code,data}=resb
				store.commit('user/M_curHeader',data)
				if(code==0){
					uni.showToast({
						title: '上传成功',
						icon:"success"
					});
				update_header({header:data})
				}
			},
		})
	}
	// 列表上传
	const selectList=(e)=>{
		// 打开相册
		uni.chooseImage({
			success:(res)=>{
				console.log(res);
			}
		})
		console.log(e);
		e.tempFiles.forEach(item=>{
			uni.uploadFile({
				url: baseUrl+'/upload/img',
				name:'file',
				filePath:item.path,
				header: {
					token:store.state.user.data.token
				},
				success: (res) => {
					console.log(res);
					let resb=JSON.parse(res.data)
					const {code,data}=resb
					if(code==0){
						addAlbum({img:data})
					}
				},
			})
		})
		uni.showToast({
			title: '上传成功',
			icon:"success"
		});
	}
	// 删除相册列表中的图片
	const deleteOne=(e)=>{
		let {id}=e.tempFile
		delAlbum({id})
	}
	onMounted(()=>{
		allAlbum()
	})
	// 请求相册
	async function allAlbum(){
		let res=await albumReq()
		if(res.data.data){
			res.data.data.forEach(item=>{
				imageList.value.push({url:baseUrl+item.img,id:item.id})
			})
		}
		
	}
	// 添加相册
	async function addAlbum(data){
		let res=await album_addReq(data)
	}
	// 删除相册
	async function delAlbum(data){
		let res=await album_delReq(data)
		if(res.data.code==0){
			uni.showToast({
				title: '删除成功',
				icon:"success"
			});
		}
	}
</script>

<style lang="scss">
.album{
	.select_img{
	}
}
</style>
